﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommonLibrary.DataModel.Basic;
using CommonLibrary.DataModel.WorkFlow;
using CommonLibrary.DataModel.Form;
using System.Xml.Linq;
using OAclient.Models;
using CommonLibrary.Common;
using System.Workflow.Activities;
using CommonLibrary.Wf.InterFace;
using ServiceApplication.Service.Basic;
using System.Data;
using ServiceApplication.Service.WorkFlow;
using ServiceApplication.Service;

namespace OAclient.Controllers
{
    public class SalaryController : Controller
    {
        //
        // GET: /Salary/

        WorkFlowService wfs = new WorkFlowService();
        BasicService bs = new BasicService();
        FormService fs = new FormService();
        SerializeDesigner designer = new SerializeDesigner();

        string wf_id = "84";
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SalarySet()
        {

            WfEntity wfEntity = wfs.QueryWf(wf_id);
            FormEntity formEntity = fs.QueryFormEntity(wfEntity.form_id);

            //ViewData["postName"] = bs.QueryPostName();
            //ViewData["rankName"] = bs.QueryRankName();

            if (formEntity == null)
            {
                return Content("不存在该表单");
            }

            var users = bs.UsersInfoForSalary();
            XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
            var elements = xml.Element("TabPage1").Elements("field");
            foreach (var item in elements)
            {
                if (item.Element("Type").Value == "BD_DataGridView")
                {
                    item.Element("GridView").Element("Rows").SetAttributeValue("FormType", "Set");
                    var rowValue = String.Empty;
                    if (users != null)
                    {
                        var rowCount = users.Rows.Count;
                        for (int index = 0; index < rowCount; index++)
                        {
                            rowValue += users.Rows[index]["部门名称"] + ";;" + users.Rows[index]["用户名称"] + ";;;;;;;;;";
                            var rowElemnt = new XElement("Row", rowValue);
                            rowElemnt.SetAttributeValue("UserId", users.Rows[index]["用户编号"]);
                            item.Element("GridView").Element("Rows").Add(rowElemnt);
                            rowValue = String.Empty;

                        }
                    }
                }
            }

            ViewData["formdefi"] = designer.DeserializeXmlToWebForSalary(xml);

            return PartialView();
        }

        public ActionResult SalaryStart(UserModel userModel)
        {
            var user_id = userModel.user.user_id.ToString();


            if (string.IsNullOrEmpty(wf_id))
            {
                return Content("不存在wf_id");
            }
            if (string.IsNullOrEmpty(user_id))
            {
                return Content("不存在user_id");
            }
            UserEntity user = bs.QueryUser(int.Parse(user_id));
            StaffEntity se = bs.QueryStaff(user.staff_id);
            DataTable dt_deptuser = bs.QueryUserByDeptId(se.dept_id.ToString());
            //获取本部门人员列表
            string[] arr_deptuser = dt_deptuser.AsEnumerable().Select(r => r["用户名称"].ToString()).ToArray();
            DeptEntity dept = bs.QueryDept(se.dept_id);
            DutyEntity duty = bs.QueryDuty(se.duty_id);
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            if (wfEntity == null)
            {
                return Content("不存在wfentity");
            }
            FormEntity formEntity = fs.QueryFormEntity(wfEntity.form_id);
            if (formEntity == null)
            {
                return Content("不存在该表单");
            }

            var users = bs.QuerySalaryInfo();
            XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
            var elements = xml.Element("TabPage1").Elements("field");
            foreach (var item in elements)
            {
                if (item.Element("Type").Value == "BD_DataGridView")
                {
                    item.Element("GridView").Element("Rows").SetAttributeValue("FormType", "Start");
                    var rowValue = String.Empty;
                    if (users != null)
                    {
                        var rowCount = users.Rows.Count;
                        for (int index = 0; index < rowCount; index++)
                        {
                            rowValue += users.Rows[index]["部门名称"] + ";" + users.Rows[index]["岗位名称"] + ";" + users.Rows[index]["用户名称"] + ";" +
                                    users.Rows[index]["级别"] + ";" + users.Rows[index]["基本工资"] + ";" + users.Rows[index]["岗位工资"] + ";" + users.Rows[index]["住房补贴"] + ";" +
                                    users.Rows[index]["手机补贴"] + ";" + users.Rows[index]["小计"] + ";" + users.Rows[index]["提成"] + ";" + users.Rows[index]["备注"];
                            var rowElemnt = new XElement("Row", rowValue);
                            rowElemnt.SetAttributeValue("UserId", users.Rows[index]["用户编号"]);
                            item.Element("GridView").Element("Rows").Add(rowElemnt);
                            rowValue = String.Empty;
                        }
                    }
                }
            }

            WorkFlowModel wfm = new WorkFlowModel();
            ViewData["formdefi"] = designer.DeserializeXmlToWebForSalary(xml);
            ViewData["form_id"] = formEntity.form_id.ToString();
            ViewData["wftemplate_id"] = wfEntity.wftemplate_id.ToString();
            ViewData["wf_id"] = wfEntity.wf_id.ToString();

            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            #region 获取下一步处理人类型
            WfClrxxInfo nextClr = wfs.getClrxxByFirstNext(platelist, wfEntity.wftemplate_id);

            //初始化选择树
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());

            if (nextClr != null)
            {
                if (nextClr.clzType == TaskClrType.由上一步处理人指定.ToString())
                {
                    ViewData["treevisible"] = "T";
                }
                else //特殊情况：ifelse活动的下一步处理人无法获取，所以不是 由上一步处理人指定 的情况，在createWorkflow 方法中clr传入null
                {
                    ViewData["treevisible"] = "F";
                }
            }
            #endregion

            return PartialView(wfm);
        }

        public ActionResult UpdateSalary(String record)
        {
            var entity = record.Split(';');
            entity[5] = String.IsNullOrEmpty(entity[5]) == true ? "/" : entity[5];
            entity[6] = String.IsNullOrEmpty(entity[6]) == true ? "/" : entity[6];
            entity[7] = String.IsNullOrEmpty(entity[7]) == true ? "/" : entity[7];
            entity[8] = String.IsNullOrEmpty(entity[8]) == true ? "/" : entity[8];

            var salaryEnty = new SalaEntity
            {
                User_Id = entity[0],
                Dept_Name = entity[1],
                Post_Name = entity[2],
                User_Name = entity[3],
                Rank_Name = entity[4],
                Base_Salary = entity[5],
                Post_Salary = entity[6],
                House_Subsidy = entity[7],
                Phone_Subsidy = entity[8],
                Summary = entity[9],
                Earn_Extern = entity[10],
                //Remark = entity[11]
            };

            //bs.UpdateSalary(salaryEnty);
            return Content("Success");
        }

        public ActionResult UpdateAllSalary(String record)
        {
            var records = record.Split(',');
            for (int i = 0; i < records.Length - 1; i++)
            {
                var entity = records[i].Split(';');
                var salaryEnty = new SalaEntity
                {
                    User_Id = entity[0],
                    Dept_Name = entity[1],
                    Post_Name = entity[2],
                    User_Name = entity[3],
                    Rank_Name = entity[4],
                    Base_Salary = entity[5],
                    Post_Salary = entity[6],
                    House_Subsidy = entity[7],
                    Phone_Subsidy = entity[8],
                    Summary = entity[9],
                    Earn_Extern = entity[10],
                    Remark = entity[11]
                };

                bs.UpdateSalary(salaryEnty);
            }
            return Content("Success");
        }

        public ActionResult AddPost(String postname)
        {
            var result = bs.AddPost(postname);
            if (result)
                return Content(bs.QueryPostName());
            else
                return Content("Fail");
        }

        public ActionResult AddRank(String rankname)
        {
            var result = bs.AddRank(rankname);
            if (result)
                return Content(bs.QueryRankName());
            else
                return Content("Fail");
        }
    }
}
